package com.zf.shuashua.advert;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;

import com.aliyun.player.AliPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.source.UrlSource;
import com.meis.base.mei.base.BaseFragment;
import com.meis.base.mei.utils.Eyes;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.AdvertUtils;
import com.zf.shuashua.MainActivity;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.bean.AdvertInfo;
import com.zf.shuashua.bean.AdvertList;
import com.zf.shuashua.bean.AdvertReport;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.common.ARouter;
import com.zf.shuashua.manager.AdDownloadManager;
import com.zf.shuashua.ui.gift.GiftFragment;
import com.zf.shuashua.ui.home.HomeFragment;

public class RewardAdvertFragment extends BaseFragment {

    private static final String ADVERT_TYPE = "advert_type";
    private static final String PLAN_ID = "plan_id";
    private static final String REPORT_ID = "report_id";
    private SurfaceView mTextureView;
    private ImageView mImgClose;
    private String mAdvertType = AdvertConstants.REWARD_TYPE_TASK;
    private String mPlanId = "";
    private String mReportID = "";
    private Handler mHandler = new Handler(Looper.getMainLooper());

    private AdvertInfo advertInfo;
    private AliPlayer aliPlayer;
    private OnRewardListener mListener;

    public void setOnRewardListener(OnRewardListener listener) {
        mListener = listener;
    }

    public static RewardAdvertFragment newInstance(String advertType, String reportId, String planId) {
        Bundle args = new Bundle();
        args.putString(ADVERT_TYPE, advertType);
        args.putString(PLAN_ID, planId);
        args.putString(REPORT_ID, reportId);
        RewardAdvertFragment fragment = new RewardAdvertFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private void dealClose(){
        AdvertReportManager.getInstance().reportAdvertAction(advertInfo, AdvertReport.EventType.VideoEnd, getReportType(), new ACallback<BaseData>() {
            @Override
            public void onSuccess(BaseData data) {
                if (data != null && data.isStatus()) {
                    getActivity().runOnUiThread(() -> {
                        if (mListener != null) {
                            mListener.onAdClose();
                        }
                    });
                }
                finish();
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                finish();
            }
        });
    }

    @Override
    protected void initView() {
        Eyes.translucentStatusBar(getActivity(), true);
        mImgClose = findViewById(R.id.img_close);
        mImgClose.setOnClickListener(v -> {
//            if (mListener != null) {
//                mListener.onAdClose();
//            }
//            finish();
            dealClose();
        });

        if (getArguments() != null) {
            mAdvertType = getArguments().getString(ADVERT_TYPE, "");
            mPlanId = getArguments().getString(PLAN_ID, "");
            mReportID = getArguments().getString(REPORT_ID, "");
        }

        aliPlayer = AliPlayerFactory.createAliPlayer(ShuaApplication.getContext());
        mTextureView = findViewById(R.id.video_view);
        mTextureView.setOnClickListener(v -> {
            if (advertInfo != null) {
                AdvertReportManager.getInstance().reportAdvertAction(advertInfo, AdvertReport.EventType.VideoClick, getReportType());
                if(advertInfo.isDownloadType()){
                    AdDownloadManager.getInstance().installApk(getActivity(), advertInfo.click_url);
                }else {
                    ARouter.getInstance().jumpH5(getActivity(), advertInfo.click_url);
                }
            }
        });
        mTextureView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (aliPlayer != null) {
                    aliPlayer.setDisplay(holder);
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (aliPlayer != null) {
                    aliPlayer.redraw();
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (aliPlayer != null) {
                    aliPlayer.setDisplay(null);
                }
            }
        });

    }

    @Override
    protected void initData() {
        loadSelfAdvert();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reward_advert;
    }

    /**
     * 下载自身广告
     */
    private void loadSelfAdvert() {
//        HttpData.getInstance().getAdvertReward(mType, new ACallback<BaseData<AdvertInfo>>() {
//            @Override
//            public void onSuccess(BaseData<AdvertInfo> data) {
//                advertInfo = data.getData();
//                if (advertInfo != null) {
//                    setupVideo(advertInfo);
//                } else {
//                    finish();
//                }
//            }
//
//            @Override
//            public void onFail(int errCode, String errMsg) {
//                finish();
//            }
//        });
        HttpData.getInstance().getPlanById(mPlanId,new ACallback<BaseData<AdvertList>>() {
            @Override
            public void onSuccess(BaseData<AdvertList> data) {
                if(data == null || data.getData() == null){
                    finish();
                    return;
                }
                AdvertList advertList = data.getData();
                if(advertList.getItems() == null || advertList.getItems().size() < 1){
                    finish();
                    return;
                }
                advertInfo = advertList.getItems().get(0);
                advertInfo.setUuid(advertList.getUuid());
                if (advertInfo != null) {
                    setupVideo(advertInfo);
                } else {
                    finish();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                finish();
            }
        });
    }

    private void setupVideo(AdvertInfo advertInfo) {
        UrlSource urlSource = new UrlSource();
        urlSource.setUri(advertInfo.origin_url);

        aliPlayer.setDataSource(urlSource);
        aliPlayer.setOnCompletionListener(() -> {
            //播放完成
//            AdvertReportManager.getInstance().reportAdvertAction(advertInfo, AdvertReport.EventType.VideoEnd, getReportType());
            if (mListener != null) {
                mListener.onVideoComplete();
            }
            mHandler.postDelayed(() -> {
                mImgClose.setVisibility(View.VISIBLE);
            }, 3000);
        });
        aliPlayer.setOnErrorListener(errorInfo -> {
            //出错事件
            if (mListener != null) {
                mListener.onVideoError();
            }
            finish();
        });
        aliPlayer.setOnPreparedListener(() -> {
            //准备成功事件
        });
        aliPlayer.setOnRenderingStartListener(() -> {
            //首帧渲染显示事件
            AdvertReportManager.getInstance().reportAdvertAction(advertInfo, AdvertReport.EventType.VideoStart, getReportType());
        });
        aliPlayer.setScaleMode(IPlayer.ScaleMode.SCALE_ASPECT_FIT);
        aliPlayer.prepare();

        aliPlayer.start();
    }

    @Override
    public void onPause() {
        if (aliPlayer != null) {
            aliPlayer.pause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        if (aliPlayer != null) {
            aliPlayer.start();
        }
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private String getShowFragment(){
        if(AdvertConstants.REWARD_TYPE_AUTO.equals(mAdvertType) || AdvertConstants.REWARD_TYPE_BUBBLE.equals(mAdvertType)){
            return HomeFragment.class.getName();
        }
        return GiftFragment.class.getName();
    }

    public void finish() {
        try {
            if (aliPlayer != null) {
                aliPlayer.stop();
                aliPlayer.release();
                aliPlayer = null;
            }
        } catch (Exception ignored) {
        }
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).backAndShowSingleFragment(this, getShowFragment());
        }else if (getActivity() instanceof com.zf.shuashua.ui.gift.H5Activity) {
            ((com.zf.shuashua.ui.gift.H5Activity) getActivity()).removeFragment(RewardAdvertFragment.class);
        }
    }

    private String getReportType() {
        return AdvertUtils.getReportType(mAdvertType, mReportID);
    }

}
